import React, { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import { Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material'

type AlertOptions = {
  title?: string
  content?: React.ReactNode
  onCancel?: () => void
  onOk?: () => void
}

// 用于存储外部传入的显示/隐藏方法
let externalSetDialogOptions: (options: AlertOptions | null) => void = () => {}

const AlertDialog: React.FC = () => {
  const { t } = useTranslation()
  const [dialogOptions, setDialogOptions] = useState<AlertOptions | null>(null)

  useEffect(() => {
    externalSetDialogOptions = setDialogOptions
  }, [])

  const handleClose = () => {
    setDialogOptions(null)
  }

  if (!dialogOptions) return null

  const {
    title,
    content,
    onCancel,
    onOk,
  } = dialogOptions

  return createPortal(
    <Dialog open onClose={handleClose} fullWidth>
      <DialogTitle>{title || t('defaultAlertTitle')}</DialogTitle>
      <DialogContent>{content}</DialogContent>
      <DialogActions>
        <Button
          onClick={() => {
            handleClose()
            if (onCancel) onCancel()
          }}
        >
          {t('dialog cancel btn')}
        </Button>
        <Button
          onClick={() => {
            handleClose()
            if (onOk) onOk()
          }}
          color="primary"
        >
          {t('dialog ok btn')}
        </Button>
      </DialogActions>
    </Dialog>,
    document.body,
  )
}

export const showAlertDialog = (options: AlertOptions) => {
  externalSetDialogOptions(options)
}

export const hideAlertDialog = () => {
  externalSetDialogOptions(null)
}

export default AlertDialog
